/*
 * Copyright (C) 2007-2012 by XDEV Software, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 3.0 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
 
package xdev.util;


import java.util.*;


public abstract class AbstractDataSource<T extends DataSource> implements DataSource<T>
{
	private String							name;
	protected final Map<String, Parameter>	params	= new Hashtable();


	public AbstractDataSource()
	{
		for(Parameter param : getDefaultParameters())
		{
			putParameter(param);
		}
	}


	public void setName(String name)
	{
		this.name = name;
	}


	@Override
	public String getName()
	{
		return name;
	}


	public <P> void putParameter(Parameter<P> param, P value)
	{
		putParameter(param.clone().setValue(value));
	}


	@Override
	public void putParameter(Parameter param)
	{
		params.put(param.getName(),param);
	}


	public void putParameterValue(String name, Object value)
	{
		getParameter(name).setValue(value);
	}


	@Override
	public Parameter getParameter(String name)
	{
		return params.get(name);
	}


	@Override
	public Parameter[] getParameters()
	{
		Parameter[] paramArray = params.values().toArray(new Parameter[params.size()]);
		Arrays.sort(paramArray);
		return paramArray;
	}


	public <P> Parameter<P> getParameter(Parameter<P> template)
	{
		return params.get(template.getName());
	}


	public <P> P getParameterValue(Parameter<P> template)
	{
		return getParameterValue(template,template.getDefaultValue());
	}


	public <P> P getParameterValue(Parameter<P> template, P defaultValue)
	{
		Parameter<P> param = getParameter(template);
		return param != null ? param.getValue() : defaultValue;
	}


	@Override
	public boolean isParameterRequired(Parameter p)
	{
		return true;
	}


	@Override
	public Parameter getDefaultParameter(String name)
	{
		for(Parameter parameter : getDefaultParameters())
		{
			if(parameter.getName().equals(name))
			{
				return parameter;
			}
		}

		return null;
	}


	/**
	 * ranks the <code>params</code> in descending order
	 * 
	 * @param params
	 */

	protected static void rankParams(Parameter... params)
	{
		for(int i = 0; i < params.length; i++)
		{
			params[i].setRank(i + 1);
		}
	}
}
